package com.rattsoftware.client.controllers;

import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.google.gwt.core.client.GWT;
import com.rattsoftware.client.AppMessages;
import com.rattsoftware.client.events.AppEvents;
import com.rattsoftware.client.service.RoleServiceAsync;
import com.rattsoftware.client.util.ProgressIndicator;
import com.rattsoftware.client.views.LoginView;

public class LoginController extends Controller {

	final AppMessages appMessages = GWT.create(AppMessages.class);
	private LoginView loginView;
	public final static EventType SESSIONTIMEOUT = new EventType();
	public final static EventType CHECKADMINPASS = new EventType();
	private RoleServiceAsync roleService;
	
	public LoginController() {
		super();
		registerEventTypes(AppEvents.Login);
		registerEventTypes(AppEvents.LoginError);
	}

	public void handleEvent(AppEvent event) {
		GWT.log("LoginController : handleEvent");
		EventType type = event.getType();
		if (type == AppEvents.Login) {
			onLogin(event);
		} else if (type == AppEvents.LoginError) {
			onError(event);
		}
	}

	public void initialize() {
		GWT.log("LoginController : initializing Login View");
		loginView = new LoginView(this);
	}

	protected void onError(AppEvent ae) {
		System.out.println("error: " + ae.<Object> getData());
	}

	private void onLogin(AppEvent event) {
		forwardToView(loginView, event);
	}

	public void doLogin(String userName, String password) {
		// TO DO do rpc here for login
		performLogin(userName, password);
	}

	public void performLogin(String username, String password) {
		ProgressIndicator.showProgressBar();
		/*userService.authenticate(username, password,
				new RattsAsyncCallback<User>() {
					@Override
					public void onSuccess(User result) {

						if (result != null) {*/
							Dispatcher dispatcher = Dispatcher.get();
							AppEvent event = new AppEvent(AppEvents.Init);
							//event.setData(result);
							dispatcher.dispatch(event);
							Dispatcher.get().dispatch(AppEvents.HomeView);
						/*} else {
							MessageBox.alert(appMessages.error(), appMessages
									.unsuccessfulLogin(),
									new Listener<MessageBoxEvent>() {

										@Override
										public void handleEvent(MessageBoxEvent be) {
											loginView.showWindow();
										}
									});
						}*/
						ProgressIndicator.hideProgressBar();
					/*}
				});*/
	}
}
